import sys, json, os
from PyQt6.QtWidgets import QApplication, QWidget, QPushButton,QVBoxLayout,QHBoxLayout
from PyQt6.QtGui import QPainter, QPen, QColor
from PyQt6.QtCore import Qt
from PyQt6.QtCore import QUrl
from PyQt6 import QtWidgets as component
from functools import partial


class MapNet(QWidget):
    def __init__(self):
        super().__init__()
        self.downloadButton = QPushButton("保存")
        self.uploadButton = QPushButton("读取")
        self.penStateList = []
        self.clear_button = QPushButton("清空")
        self.paint = False
        self.state = 1
        self.view_x = None
        self.setMouseTracking(True)
        self.view_y = None
        self.color = [Qt.GlobalColor.white, Qt.GlobalColor.black, Qt.GlobalColor.blue, Qt.GlobalColor.yellow, Qt.GlobalColor.green,
                      Qt.GlobalColor.red, Qt.GlobalColor.cyan, Qt.GlobalColor.gray, Qt.GlobalColor.magenta, Qt.GlobalColor.darkGreen]

        self.map = [[[0, round(-5 + k * 0.2, 2), round(5 - i * 0.2, 2)] for k in range(50)] for i in range(50)]
        self.init()

    def save(self):
        filePath, _ = component.QFileDialog.getSaveFileName(
            self,
            "选择保存的位置",
            "", 
            "JSON Files (*.json)"                                    
        )
        if not filePath:
            self.pop_window("未选择文件！")
        else:
            with open(filePath, 'w+') as file:
                file.write(json.dumps({
                    'map': self.map
                }))
            self.pop_window("保存成功！")

    def load(self):
        filePath, _ = component.QFileDialog.getOpenFileUrl(
            self,
            "选择载入的文件",
            QUrl(),
            "JSON File(*.json)"
        )
        if not filePath.isValid():
            self.pop_window("未选择文件！")
        else:
            filePath = filePath.toLocalFile()
            with open(filePath, 'r') as file:
                data_str = file.read()
            try:
                tempdic = json.loads(data_str)
                self.map = tempdic['map']
                self.pop_window("读取成功")
                self.update()
            except:
                self.pop_window("json文件异常")


    def pop_window(self, text):
        pop = component.QMessageBox()
        pop.setWindowTitle("提示")
        pop.setText(text)
        pop.setStandardButtons(component.QMessageBox.StandardButton.Ok)
        pop.exec()

    def init(self):
        # 初始化笔盒
        for i in range(10):
            temp_button = QPushButton(str(i))
            temp_button.clicked.connect(partial(self.change_state, i))
            self.penStateList.append(temp_button)
            
        ## 绑定保存和读取事件
        self.downloadButton.clicked.connect(self.save)
        self.uploadButton.clicked.connect(self.load)

        # 绑定清空事件
        self.clear_button.clicked.connect(self.clear)

        # 窗口初始化
        self.resize(800, 600)
        self.setWindowTitle('MapNet')
        self.gridInit()
        self.show()
    
    def paintEvent(self, e):
        qp = QPainter()
        qp.begin(self)
        self.drawFrame(qp)
        qp.end()
    
    def change_state(self, state):
        self.state = state
    
    def drawFrame(self, qp: QPainter):
        qp.setBrush(Qt.GlobalColor.white)
        qp.drawRect(0, 0, 600, 600)

        for row in range(50):
            for col in range(50):
                qp.setBrush(self.color[self.map[row][col][0]])
                qp.drawRect(col * 12, row * 12, 12, 12)

    def gridInit(self):
        self.mainView = QHBoxLayout()

        #首先创建两个垂直布局
        self.colOne = QVBoxLayout()
        self.colTwo = QVBoxLayout()

        # 添加文本
        text = component.QPlainTextEdit("笔盒")
        text.setReadOnly(True)
        # font_metrics = text.fontMetrics()
        # line_height = font_metrics.lineSpacing()
        # # 适当增加一些额外高度以适应边框等
        text.setFixedHeight(20) 
        self.colTwo.addWidget(text)

        # 第二块添加按钮
        # 添加笔盒选项
        for i in range(5):
            tempRow = QHBoxLayout()
            tempRow.addWidget(self.penStateList[i * 2])
            tempRow.addWidget(self.penStateList[i * 2 + 1])
            self.colTwo.addLayout(tempRow)

        # 坐标指示框
        label_x = component.QLabel("X: ")
        self.view_x = component.QLabel()
        self.view_x.setFixedHeight(20)
        
        label_y = component.QLabel("Y: ")
        self.view_y = component.QLabel()
        self.view_y.setFixedHeight(20)

        self.colTwo.addWidget(label_x)
        self.colTwo.addWidget(self.view_x)
        self.colTwo.addWidget(label_y)
        self.colTwo.addWidget(self.view_y)

        self.colTwo.addStretch(1)
        self.colTwo.addWidget(self.downloadButton)
        self.colTwo.addWidget(self.uploadButton)

        # 新添一个清空按钮
        self.colTwo.addWidget(self.clear_button)


        self.mainView.addLayout(self.colOne)
        self.mainView.addLayout(self.colTwo)

        self.mainView.setStretch(0, 6)
        self.mainView.setStretch(1, 1)
        
        self.setLayout(self.mainView)

    def mouseMoveEvent(self, event):
        def get_pos(x, y):
            return [int(x // 12), int(y // 12)]
        x = event.position().x()
        y = event.position().y()
        x, y = get_pos(x, y)
        if x >= 0 and x < 50 and y >= 0 and y < 50:
            if self.paint:
                self.map[y][x][0] = self.state
                self.update()
            self.view_x.setText(str(self.map[y][x][1]))
            self.view_y.setText(str(self.map[y][x][2]))

    def mousePressEvent(self, event):
        self.paint = True
    
    def mouseReleaseEvent(self, event):
        self.paint = False
    
    def clear(self):
        for i in range(50):
            for j in range(50):
                self.map[i][j][0] = 0
        self.update()


def main():

    app = QApplication(sys.argv)
    window = MapNet()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()